var express = require('express');
var router = express.Router();
var jwt = require('jwt-simple');//token令牌
var moment = require('moment');
var config = require('config-lite');

var UserModel = require('../../models/user');
var checkToken = require("../../middleware/checkToken");
var errPock = require('../../middleware/errPack');

//用户获取信息
router.get('/', checkToken.get, function (req, res, next) {
    if(req.user) {
      res.send(req.user);
    }
})
// POST /signin 用户登录
router.post('/', function (req, res, next) {
  var fields = {
      name : req.fields.name,
      password : req.fields.password
    }

  UserModel.getUserSign({name: fields.name})
    .then(function (user) {
      if(!user || !(user.password === fields.password)) {
        return errPock( res, 1000);
      }
      //设置一个过期时间
      var expires = moment().add(7, 'minutes').valueOf();
      var token = jwt.encode({
        iss: user.name,
        exp: expires
      }, config.TokenSecret);

      res.send(token);
    }, function (err) {
      res.send('error');
    })
});

module.exports = router;
